<?php

namespace zhtfrontend\controllers;

use common\components\helpers\Fun;
use yii\helpers\ArrayHelper;
use yii\web\BadRequestHttpException;
use yii\widgets\ActiveForm;
use zhtfrontend\models\datas\Admin;
use zhtfrontend\models\datas\Mechanic;
use zhtfrontend\models\datas\MechanicSettlement;
use zhtfrontend\models\datas\MechanicSettlementRelation;
use zhtfrontend\models\datas\MechanicSettlementVoucher;
use zhtfrontend\models\datas\MechanicSubsidy;
use yii\web\Response;
use yii\data\Pagination;

class MechanicsettlementController extends \zhtfrontend\components\bases\BaseController
{
    public function actionIndex()
    {
        $param = \Yii::$app->request->get();
        $model = MechanicSettlement::find();
        if (!empty($param['start']) && !empty($param['end'])) {
            $start_time = strtotime(trim($param['start']));
            $end_time = strtotime(trim($param['end']).' 23:59:59');
            $msIds = MechanicSubsidy::find()->select('id')->where(['between','class_date',$start_time,$end_time])->column();
            $ids = MechanicSettlementRelation::find()->select('mechanic_settlement_id')->where(['mechanic_subsidy_divided_id'=>$msIds,'type'=>1])->column();
            $model->where(['id'=>$ids]);
        }
        if(!empty($param['mechanic_id'])){
            $model->andWhere(['mechanic_id'=>$param['mechanic_id']]);
        }
        if(isset($param['status_id']) && $param['status_id'] != null){
            $model->andWhere(['status'=>$param['status_id']]);
        }
        $model->orderBy('id DESC');
        $pages = new Pagination(['totalCount' => $model->count(), 'pageSize' => 12]);
        isset($param['page']) ? $pages->page = $param['page'] - 1 : 0;
        $data = $model->offset($pages->offset)->limit($pages->limit)->all();
        $data = Fun::asArray($data,['mechanic_name','status_name']);
        $mechanic_ids = MechanicSubsidy::find()->select('mechanic_id')->groupBy('mechanic_id')->column();
        $mechanicList = Mechanic::find()->where(['id'=>$mechanic_ids])->all();
        $mechanicList = ArrayHelper::map($mechanicList,'id','name');

        $start = !empty($param['start'])?$param['start']:null;
        $end = !empty($param['end'])?$param['end']:null;

        return $this->render('index',['data'=>$data,'pages'=>$pages,'start'=>$start,'end'=>$end,'mechanicList'=>$mechanicList]);
    }

    public function actionSettlement(){
        $id = \Yii::$app->request->get('id');
        if($id == null){
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $modelRow = MechanicSubsidy::findOne($id);
        $amount = MechanicSubsidy::find()->where(['id'=>$id,'status'=>0])->sum('amount');
        $model = MechanicSubsidy::find()->where(['id'=>$id,'status'=>0])->all();
        $data = Fun::asArray($model,['mechanic_name','goods_name','status_name']);
        if(\Yii::$app->request->isPost && \Yii::$app->request->post()){
            $post = \Yii::$app->request->post();
            if(empty($post['ids'])){
                return $this->redirectMessage('系统错误请重试！',Fun::url(['mechanicsettlement/settlements','id'=>$id]));
            }
            $amounts = MechanicSubsidy::find()->where(['id'=>$post['ids']])->sum('amount');
            $MechanicSettlementModel = new MechanicSettlement();
            $MechanicSettlementModel->mechanic_id = $modelRow->mechanic_id;
            $MechanicSettlementModel->commission_money = $amounts;
            $MechanicSettlementModel->operator = \Yii::$app->user->identity->name;
            $MechanicSettlementModel->operator_id = \Yii::$app->user->id;
            $MechanicSettlementModel->type = 1;
            if($MechanicSettlementModel->save(false)){
                foreach ($post['ids'] as $val){
                    $mechanicSettlementRelation = new MechanicSettlementRelation();
                    $mechanicSettlementRelation->mechanic_settlement_id = $MechanicSettlementModel->id;
                    $mechanicSettlementRelation->mechanic_subsidy_divided_id = (int)$val;
                    $mechanicSettlementRelation->type = 1;
                    $mechanicSettlementRelation->save(false);
                }
            }
            MechanicSubsidy::updateAll(['status'=>1,'settlement_time'=>time()],['id'=>$post['ids']]);
            return $this->redirectMessage('结算成功！',Fun::url(['mechanicsettlement/details','id'=>$MechanicSettlementModel->id]));
        }

        return $this->render('settlement',['data'=>$data,'amount'=>$amount,'start'=>null,'end'=>null]);
    }

    public function actionSettlements(){
        $id = \Yii::$app->request->get('id');
        $start = trim(\Yii::$app->request->get('start'));
        $end = trim(\Yii::$app->request->get('end'));
        if($id == null){
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $amountModel = MechanicSubsidy::find()->where(['mechanic_id'=>$id,'status'=>0]);
        $model = MechanicSubsidy::find()->where(['mechanic_id'=>$id,'status'=>0]);
        if ($start != null && $end != null) {
            $start_time = strtotime($start);
            $end_time = strtotime($end.' 23:59:59');
            $model->andWhere(['between','class_date',$start_time,$end_time]);
            $amountModel->andWhere(['between','class_date',$start_time,$end_time]);
        }
        $data = $model->all();
        $data = Fun::asArray($data,['mechanic_name','goods_name','status_name']);
        $amount = $amountModel->sum('amount');
        if(\Yii::$app->request->isPost && \Yii::$app->request->post()){
            $post = \Yii::$app->request->post();
            if(empty($post['ids'])){
                return $this->redirectMessage('系统错误请重试！',Fun::url(['mechanicsettlement/settlements','id'=>$id,'start'=>$start,'end'=>$end]));
            }
            $amount = MechanicSubsidy::find()->where(['id'=>$post['ids']])->sum('amount');
            $MechanicSettlementModel = new MechanicSettlement();
            $MechanicSettlementModel->mechanic_id = $id;
            $MechanicSettlementModel->commission_money = $amount;
            $MechanicSettlementModel->operator = \Yii::$app->user->identity->name;
            $MechanicSettlementModel->operator_id = \Yii::$app->user->id;
            $MechanicSettlementModel->type = 1;
            if($MechanicSettlementModel->save(false)){
                foreach ($post['ids'] as $val){
                    $mechanicSettlementRelation = new MechanicSettlementRelation();
                    $mechanicSettlementRelation->mechanic_settlement_id = $MechanicSettlementModel->id;
                    $mechanicSettlementRelation->mechanic_subsidy_divided_id = (int)$val;
                    $mechanicSettlementRelation->type = 1;
                    $mechanicSettlementRelation->save(false);
                }
            }
            MechanicSubsidy::updateAll(['status'=>1,'settlement_time'=>time()],['id'=>$post['ids']]);
            return $this->redirectMessage('结算成功！',Fun::url(['mechanicsettlement/details','id'=>$MechanicSettlementModel->id]));
        }

        return $this->render('settlement',['data'=>$data,'amount'=>$amount,'start'=>$start,'end'=>$end]);
    }

    public function actionDetails(){
        $id = \Yii::$app->request->get('id');
        if($id == null){
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $model = MechanicSettlement::findOne($id);
        $mechanic_subsidy_ids = MechanicSettlementRelation::find()->select('mechanic_subsidy_divided_id')->where(['mechanic_settlement_id'=>$id])->column();

        $modelList = MechanicSubsidy::find()->where(['id'=>$mechanic_subsidy_ids])->all();
        $data = Fun::asArray($modelList,['goods_name']);

        $VoucherList = MechanicSettlementVoucher::find()->where(['mechanic_settlement_id'=>$id])->all();

        return $this->render('details',['data'=>$data,'model'=>$model,'VoucherList'=>$VoucherList]);
    }


    //付款
    public function actionPayment(){
        $this->layout = '@app/views/layouts/iframe.php';
        $id = \Yii::$app->request->get('id');
        if($id == null){
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }

        $model = MechanicSettlement::findOne($id);
        $model->operator_id = \Yii::$app->user->id;
        $payment = \Yii::$app->params['payment'];
        $finance = Admin::find()->where(['role'=>'finance','status'=>1])->all();
        $finance = ArrayHelper::map($finance,'id','name');
        if (\Yii::$app->request->isAjax && \Yii::$app->request->post('ajax') == 'w0' && $model->load(\Yii::$app->request->post())) {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model);
        }
        if($model->load(\Yii::$app->request->post()) && $model->validate()){
            $model->payment_method = $payment[$model->payment_id];
            $model->payment_time = time();
            $model->paymant_operator =  $finance[$model->paymant_operator_id];
            $model->picture = '';
            if($model->save(false)){
                if(!empty($model->imageList)){
                    $imagelist = $model->imageList;
                    $imagelist_arr = explode('#|#',$imagelist);
                    foreach ($imagelist_arr as $val){
                        $voucherModel = new MechanicSettlementVoucher();
                        $voucherModel->mechanic_settlement_id = $model->id;
                        $voucherModel->voucher_url = $val;
                        $voucherModel->operator = \Yii::$app->user->identity->name;
                        $voucherModel->operator_id = \Yii::$app->user->id;
                        $voucherModel->save(false);
                    }
                }
            }
            return $this->redirectMessage('付款成功！',Fun::url(['mechanicsettlement/details','id'=>$id]));
        }
        return $this->render('payment',['model'=>$model,'payment'=>$payment,'finance'=>$finance]);
    }

    //上传凭证
    public function actionVoucher(){
        $this->layout = '@app/views/layouts/iframe.php';
        $id = \Yii::$app->request->get('id');
        if($id == null){
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $model = MechanicSettlement::findOne($id);
        if($model->load(\Yii::$app->request->post()) ){
            if(!empty($model->imageList)){
                $imagelist = $model->imageList;
                $imagelist_arr = explode('#|#',$imagelist);
                foreach ($imagelist_arr as $val){
                    $voucherModel = new MechanicSettlementVoucher();
                    $voucherModel->mechanic_settlement_id = $model->id;
                    $voucherModel->voucher_url = $val;
                    $voucherModel->operator = \Yii::$app->user->identity->name;
                    $voucherModel->operator_id = \Yii::$app->user->id;
                    $voucherModel->save(false);
                }
            }
            return $this->redirectMessage('付款成功！',Fun::url(['mechanicsettlement/details','id'=>$id]));
        }
        return $this->render('voucher',['model'=>$model]);
    }

}
